﻿using Asteroids.Entities.Components;
using Asteroids.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Asteroids.Entities.EntityProcessors
{
    public class PrimitiveRenderingProcessor : EntityProcessor
    {
        private PrimitiveBatch _primitiveBatch;

        public PrimitiveRenderingProcessor(IGraphicsDeviceService graphicsDeviceService)
        {
            _primitiveBatch = new PrimitiveBatch(graphicsDeviceService.GraphicsDevice);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_primitiveBatch != null)
                    _primitiveBatch.Dispose();
            }
        }

        public override void Process(Entity e)
        {
            TransformComponent transform = e.QueryComponent<TransformComponent>();
            VertexPrimitiveRenderComponent vertexComponent = e.QueryComponent<VertexPrimitiveRenderComponent>();

            if (transform != null && vertexComponent != null)
            {
                if (vertexComponent.Visible)
                {
                    _primitiveBatch.Begin(vertexComponent.PrimitiveType);

                    var model = vertexComponent.Model;
                    // Matrix translationOrigin = Matrix.CreateTranslation(new Vector3(vertexComponent.Origin, 0));
                    Matrix translateLocation = Matrix.CreateTranslation(new Vector3(transform.Location, 0));
                    Matrix scale = Matrix.CreateScale(vertexComponent.Scale);
                    Matrix rotation = Matrix.CreateRotationZ(transform.Rotation);

                    Matrix translation = (rotation * scale) * translateLocation;

                    for (int vertexIndex = 0; vertexIndex < model.Length; vertexIndex++)
                    {
                        var vert = model[vertexIndex];
                        Vector2.Transform(ref vert.Position, ref translation, out vert.Position);
                        _primitiveBatch.AddVertex(vert.Position, vert.Color);
                    }

                    _primitiveBatch.End();
                }
            }
        }
    }
}
